package mapEditor.view.resItemEdit
{
	import flash.display.Sprite;
	import flash.events.Event;
	
	import mapEditor.MapEditorManager;
	import mapEditor.data.ResTemplateInfo;
	import mapEditor.events.MapEditorEvent;
	import mapEditor.vo.ResItemVO;
	
	import utils.DisplayUtil;

	public class ResItemListView extends Sprite
	{
		private var _resItemItemList:Vector.<ResItemItemView>=new Vector.<ResItemItemView>();
		private var _editItemView:ResItemItemView;
		private var _selectItemView:ResItemItemView;
		
		public function ResItemListView()
		{
			ResTemplateInfo.instance.addEventListener(MapEditorEvent.RES_CHANGE, __onResChange);
			loadItemLib();
		}
		
		private function __onResChange(evt:MapEditorEvent):void
		{
			loadItemLib();
		}
		
		/**
		 *载入单项库
		 */		
		private function loadItemLib():void
		{
			clearItemList();
			for each(var resItemVO:ResItemVO in ResTemplateInfo.instance.res)
			{
				var resItemItemView:ResItemItemView=new ResItemItemView(resItemVO);
				resItemItemView.addEventListener(MapEditorEvent.EDITING, __onItemViewEdit);
				resItemItemView.addEventListener(MapEditorEvent.SELECTED, __onItemViewSelect);
				resItemItemView.x=0;
				resItemItemView.y=_resItemItemList.length*resItemItemView.height+_resItemItemList.length*5;
				addChild(resItemItemView);
				_resItemItemList.push(resItemItemView);
			}
			dispatchEvent(new Event(Event.CHANGE));
		}
		
		private function __onItemViewSelect(evt:MapEditorEvent):void
		{
			if(_selectItemView)_selectItemView.isSelected=false;
			_selectItemView=evt.currentTarget as ResItemItemView;
			dispatchEvent(new Event(Event.SELECT));
		}
		
		private function __onItemViewEdit(evt:MapEditorEvent):void
		{
			if(_editItemView)_editItemView.isEdit=false;
			_editItemView=evt.target as ResItemItemView;
			MapEditorManager.instance.selectResItemItem(_editItemView.resItemVO);
		}
		
		private function clearItemList():void
		{
			while(_resItemItemList.length>0)
			{
				var resItemItemView:ResItemItemView=_resItemItemList.shift();
				resItemItemView.removeEventListener(MapEditorEvent.EDITING, __onItemViewEdit);
				resItemItemView.removeEventListener(MapEditorEvent.SELECTED, __onItemViewSelect);
				DisplayUtil.dispose(resItemItemView);
				resItemItemView=null;
			}
		}
		
		public function dispose():void
		{
			ResTemplateInfo.instance.removeEventListener(MapEditorEvent.RES_CHANGE, __onResChange);
			clearItemList();
			_resItemItemList=null;
			_editItemView=null;
			_selectItemView=null;
		}

		public function get selectItemView():ResItemItemView
		{
			return _selectItemView;
		}
	}
}